
/**
 * 将十六进制颜色值转换为rgba
 * @param {Object} color
 * @param {Object} opacity
 */
export function hexToRGB(color,opacity){
	let newColor = 'rgba(';

	//判断是三位还是六位
	if(color.length === 4){
		let arry = [];
		for(let i = 1;i < color.length;i++){
			arry.push(parseInt("0x" + color[i] + color[i]));
		}
		arry.forEach(function(item){
			newColor += item + ', ';
		});
		newColor += opacity/100 + ')';
		return newColor;
	}

  let arry = [];
  for(let i = 1;i < color.length;i += 2){
    arry.push(parseInt("0x" + color.slice(i,i+2)));
  }
  arry.forEach(function(item){
    newColor += item + ', ';
  });
  newColor += opacity/100 + ')';
  return newColor;
}
/**
 * 将rgba颜色值转换为十六进制
 * @param {Object} rgba
 */
export function RGBToHex(rgba){
	let str = rgba.slice(5,rgba.length - 1),
		arry = str.split(','),
		opa = Number(arry[3].trim())*100,
		strHex = "#",
		r = Number(arry[0].trim()),
		g = Number(arry[1].trim()),
		b = Number(arry[2].trim());

	strHex += ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

    return {color:strHex,opacity:opa};
}

/**
 * 正则检测rgba格式是否正确
 * @param {Object} rgba
 */
export function checkRGBA(rgba){
	let str = rgba.slice(5,rgba.length - 1),
    	arry = str.split(','),
    	status = true,
		reg = /^rgba\(\d{1,3}(\,\s{0,1}\d{1,3}){2}\,\s{0,1}(0|(0(\.\d{1,2}))|1)\)$/;

	arry.forEach(function(item,index){
		if(index == arry.length - 1){
			if(Number(item.trim()) < 0 || Number(item.trim()) > 1){
				status = false;
			}
		}else{
			if(Number(item.trim()) < 0 || Number(item.trim()) > 255){
				status = false;
			}
		}
	});

	return reg.test(rgba) && status;
}
